/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    bool btreeGameWinningMove(TreeNode *root, int n, int x)
    {
        TreeNode *xNode = dfsSearchVal(root, x);
        int threshold = n / 2;
        int leftSubTreeSize = treeNodeCount(xNode->left);
        if (leftSubTreeSize > threshold)
        {
            return true;
        }
        int rightSubTreeSize = treeNodeCount(xNode->right);
        if (rightSubTreeSize > threshold)
        {
            return true;
        }
        if (n - leftSubTreeSize - rightSubTreeSize - 1 > threshold)
        {
            return true;
        }
        return false;
    }

    TreeNode *dfsSearchVal(TreeNode *root, int val)
    {
        if (root == nullptr)
        {
            return nullptr;
        }
        if (root->val == val)
        {
            return root;
        }
        TreeNode *leftResult = dfsSearchVal(root->left, val);
        if (leftResult != nullptr)
        {
            return leftResult;
        }
        TreeNode *rightResult = dfsSearchVal(root->right, val);
        if (rightResult != nullptr)
        {
            return rightResult;
        }
        return nullptr;
    }

    int treeNodeCount(TreeNode *root)
    {
        if (root == nullptr)
        {
            return 0;
        }
        return 1 + treeNodeCount(root->left) + treeNodeCount(root->right);
    }
};